package com.xone.collaboration.service.impl.strategy;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.xone.collaboration.dao.dataobject.Layer;
import com.xone.collaboration.dao.mapper.LayerMapper;
import com.xone.collaboration.service.OpStrategy;
import com.xone.collaboration.service.aonntation.Strategy;
import com.xone.collaboration.service.impl.process.OperationContext;
import com.xone.collaboration.service.vo.OperationResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Strategy("INSERT")
@Component
@Slf4j
public class InsertOpStrategy implements OpStrategy {

    @Autowired
    private LayerMapper mapper;

    @Override
    public OperationResult operate(OperationContext context) {
        try{
            List<Layer> layerList = Lists.newArrayList();
            context.getElements().forEach(element->{
                Layer layer = new Layer();
                layer.setCreator(context.getOperator());
                layer.setModifier(context.getOperator());
                layer.setGmtCreate(new Date());
                layer.setGmtModified(new Date());
                layer.setElementType(element.getElementType().getValue());
                layer.setElementContent(element.getElementContent());
                layer.setPriority(Short.valueOf(element.getPriority().toString()));
                layer.setSketchpadId(context.getSketchId());
                layer.setExtension(JSON.toJSONString(element.getExtension()));
                layer.setLayerId(element.getLayerId());
                layerList.add(layer);
            });
            mapper.insertBatch(layerList);
            log.info("insert layer success");
        }catch (Exception e){
            log.error("insertBatch layer error:",e);
            return OperationResult.of(false,e.getMessage());
        }

        return OperationResult.of(true,null);
    }
}
